package com.tempjob.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author hui
 * @Date 22-3-9 上午9:41
 **/
@Configuration
public class RedisConfig {

    //JedisPoolConfig
    @Value("${redis.jedisPoolConfig.maxTotal}")
    private int maxTotal;
    @Value("${redis.jedisPoolConfig.maxIdle}")
    private int maxIdle;
    @Value("${redis.jedisPoolConfig.maxWaitMillis}")
    private long maxWaitMillis;
    @Value("${redis.jedisPoolConfig.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;
    @Value("${redis.jedisPoolConfig.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${redis.jedisPoolConfig.minEvictableIdleTimeMillis}")
    private long minEvictableIdleTimeMillis;
    @Value("${redis.jedisPoolConfig.softMinEvictableIdleTimeMillis}")
    private long softMinEvictableIdleTimeMillis;
    @Value("${redis.jedisPoolConfig.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${redis.jedisPoolConfig.jmxEnabled}")
    private boolean jmxEnabled;
    @Value("${redis.jedisPoolConfig.blockWhenExhausted}")
    private boolean blockWhenExhausted;
    @Value("${redis.jedisPoolConfig.numTestsPerEvictionRun}")
    private int numTestsPerEvictionRun;

    @Value("${redis.timeout:2000}")
    private Integer timeout;
    @Value("${redis.password:}")
    private String password;

    @Value("${redis.cluster.clutterUrl}")
    private String clutterUrl;

    @Bean(name = "jedisPoolConfig")
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig c = new JedisPoolConfig();
        c.setMaxTotal(maxTotal);
        c.setMaxIdle(maxIdle);
        c.setMaxWaitMillis(maxWaitMillis);
        c.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        c.setTestOnBorrow(testOnBorrow);
        c.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        c.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
        c.setTestWhileIdle(testWhileIdle);
        c.setJmxEnabled(jmxEnabled);
        c.setBlockWhenExhausted(blockWhenExhausted);
        c.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        return c;
    }

    @Bean
    public RedisSentinelConfiguration sentinelConfiguration(){
        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
        //配置redis的哨兵sentinel
        Set<RedisNode> redisNodeSet = new HashSet<>();
        redisNodeSet.add(new RedisNode(clutterUrl.split(":")[0],Integer.parseInt(clutterUrl.split(":")[1])));
        redisSentinelConfiguration.setSentinels(redisNodeSet);
        redisSentinelConfiguration.setPassword(password);
        return redisSentinelConfiguration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        JedisConnectionFactory jedisConnectionFactory = null;
        String[] url = clutterUrl.split(":");
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(url[0]);
        redisStandaloneConfiguration.setPassword(password);
//        redisStandaloneConfiguration.setDatabase(Integer.parseInt(database));
        redisStandaloneConfiguration.setPort(Integer.valueOf(url[1]));
        JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
        jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));
        JedisClientConfiguration jedisClientConfigurationNew = jedisClientConfiguration.usePooling().poolConfig(jedisPoolConfig).build();
        jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,jedisClientConfigurationNew);
        return jedisConnectionFactory;
    }


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        //为了开发的方便，一般直接使用<String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        //json的序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance ,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //String的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);

        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;
    }



}
